package cn.zhaoyuening.chat_client.handler;

import cn.zhaoyuening.chat_client.utils.ClientConstant;
import cn.zhaoyuening.chat_common.msg.BaseMsg;
import cn.zhaoyuening.chat_common.msg.ChatMsg;
import cn.zhaoyuening.chat_common.msg.PingMsg;
import cn.zhaoyuening.zamh.manager.MsgManager;
import cn.zhaoyuening.zamh.msg.Msg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by Buynow on 2017/6/14.
 */
public class ChatClientHandler extends SimpleChannelInboundHandler<BaseMsg> {

    private MsgManager msgManager;

    public ChatClientHandler(MsgManager msgManager) {
        this.msgManager = msgManager;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //空闲时发送心跳包
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    PingMsg pingMsg = new PingMsg();
                    ctx.writeAndFlush(pingMsg);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, BaseMsg msg) throws Exception {
        switch (msg.getType()) {
            case PING:
                break;
            case CHAT:
                showMsg((ChatMsg) msg);
                break;
        }
    }

    private void showMsg(ChatMsg chatMsg) {
        Msg msg = new Msg(ClientConstant.ACCEPT_CHAT_MSG, chatMsg);
        msgManager.sendMsg(msg);
    }
}
